package com.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.UserInfoBean;
import com.project.result.GlobalHandleException;
import com.project.result.ResponseResult;
import com.project.result.ResultCode;
import com.project.service.IUserInfoService;
import com.project.util.JWTUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
@ResponseResult
public class UserInfoController {

    @Resource
    private IUserInfoService userInfoService;

    @PostMapping("/login")
    public Object login(String username, String password) throws GlobalHandleException {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_name",username);
        wrapper.eq("user_pass",password);

        UserInfoBean userInfoBean = userInfoService.getOne(wrapper);

        if(userInfoBean == null){
            throw new GlobalHandleException(ResultCode.USER_LOGIN_ERROR);
        }

        String token = JWTUtil.createToken(userInfoBean.getUsername(),userInfoBean.getPassword(), Calendar.MINUTE,21);
        String refreshToken = JWTUtil.createToken(userInfoBean.getUsername().toString(),userInfoBean.getUsername(), Calendar.DATE,7);
        Map map = new HashMap();
        map.put("token",token);
        map.put("refreshToken",refreshToken);

        return map;
    }

}
